import asyncio
import io
import json
import os

from fastapi import HTTPException

FILE_DIRECTORY = 'excel_results'


def delete_files_in_folder(folder_path: str, file_names: list):
    """
    删除指定文件夹下的多个文件

    :param folder_path: 文件夹路径
    :param file_names: 要删除的文件名列表
    """
    for file_name in file_names:
        file_path = os.path.join(folder_path, file_name)
        # file_path = file_name
        try:
            if os.path.exists(file_path):
                os.remove(file_path)
                print(f"Deleted file: {file_path}")
            else:
                print(f"File not found: {file_path}")
        except Exception as e:
            print(f"Error deleting file: {file_path}, {e}")


def remove_file(file_path: str):
    """删除文件"""
    try:
        os.remove(file_path)
        print(f"File {file_path} deleted.")
    except Exception as e:
        print(f"Error deleting file {file_path}: {e}")


async def remove_file1(file_path: str, delay: int):
    """删除文件"""
    try:
        await asyncio.sleep(delay)
        os.remove(file_path)
        print(f"File {file_path} deleted.")
    except Exception as e:
        print(f"Error deleting file {file_path}: {e}")


def read_excel_file(file_name):
    file_path = os.path.join(FILE_DIRECTORY, file_name)
    if not os.path.exists(file_path) or not file_path.endswith('.xlsx'):
        raise HTTPException(status_code=404, detail="File not found")

    with open(file_path, 'rb') as f:
        return io.BytesIO(f.read())




def generate_response(excel_data, json_data):
    # 生成多部分响应
    boundary = "simple-boundary"
    yield f"--{boundary}\r\n"
    yield 'Content-Disposition: form-data; name="json"\r\n'
    yield "Content-Type: application/json\r\n\r\n"
    yield json.dumps(json_data) + "\r\n"

    yield f"--{boundary}\r\n"
    yield 'Content-Disposition: form-data; name="file"; filename="data.xlsx"\r\n'
    yield "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n"
    while chunk := excel_data.read(8192):
        yield chunk
    yield "\r\n"

    yield f"--{boundary}--\r\n"





# def generate_response(excel_data, json_data):
#     yield json.dumps(json_data)
